from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.decorators import action
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from users.models import User
from users import serializers
from . import constants
from goods.models import SKU
from goods.serializers import SKUSerializer
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.
class UsernameCountView(APIView):
    """验证用户名是否重复"""

    def get(self, request, username):
        # 查询数据库获取username数量
        count = User.objects.filter(username=username).count()

        # 组织响应数据
        data = {
            'username': username,
            'count': count,
        }

        # 返回响应
        return Response(data)


class MoblieCountView(APIView):
    """验证手机号是否重复"""

    def get(self, request, mobile):
        # 查询数据库获取mobile数量
        count = User.objects.filter(mobile=mobile).count()

        # 组织响应数据
        data = {
            'mobile': mobile,
            'count': count,
        }

        # 返回响应
        return Response(data)


class UserView(CreateAPIView):
    """用户注册"""

    serializer_class = serializers.CreateUserSerializer


class UserCenterView(RetrieveAPIView):
    """用户中心"""

    # 指定所用的序列化器类
    serializer_class = serializers.UserCenterSerializer

    # 在视图访问前也进行用户权限认证:JWT认证
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """重写此方法获取登录用户"""
        return self.request.user


class UpdateEmailView(UpdateAPIView):
    """添加邮箱到数据库"""

    # 用户登录状态验证
    permission_classes = [IsAuthenticated]

    # 指定序列化器类
    serializer_class = serializers.UpdateEmailSerializer

    def get_object(self):
        """重写get_object()获取登录用户"""
        return self.request.user


class VerifyEmailView(APIView):
    """验证邮件验证是否通过"""

    def get(self, request):
        """获取邮箱验证结果"""
        # 1.获取参数
        token = request.query_params.get('token')

        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.调用方法验证token是否有效
        user = User.verify_email_method(token)

        if not user:
            return Response({'message': '链接已失效'}, status=status.HTTP_400_BAD_REQUEST)

        # 用户存在，则验证通过，并设置user邮箱激活状态为激活
        user.email_active = True
        user.save()

        # 返回
        return Response({'message': 'OK'})


class AddressView(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    """用户地址管理:增/改/删"""
    # 1.指定序列化器类
    serializer_class = serializers.UserAddressSerializer
    # 2.权限验证:登录后才能进行操作
    permission_classes = [IsAuthenticated]

    # 重写获取查询集函数
    def get_queryset(self):
        # 获取用户所有的未被逻辑删除的收货地址
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """重写获取数据列表行为list"""
        # 获取查询集
        queryset = self.get_queryset()
        # 获取序列化器对象,并传入要进行序列化的查询集
        serializer = self.get_serializer(queryset, many=True)
        # 获取当前登录用户
        user = self.request.user
        # 将序列化后的数据返回给前端
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """保存用户地址数据"""
        # 查询用户收货地址数量
        count = request.user.addresses.count()
        # 判断用户收货地址数量是否超出
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据数量已达上限'}, status=status.HTTP_400_BAD_REQUEST)

        # 调用父类create方法创建收货地址并返回
        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """删除收货地址"""
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        # 返回响应
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """设置默认地址"""
        address = self.get_object()
        request.user.default_address = address
        request.user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """修改标题"""
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


class AddUserBrowseHistoryView(CreateModelMixin, GenericAPIView):
    """用户浏览历史记录"""
    # 验证用户是否登录
    permission_classes = [IsAuthenticated]

    # 指定进行验证的序列化器类
    serializer_class = serializers.AddUserBrowseHistorySerialzier

    def post(self, request):
        """创建浏览记录"""
        # 调用CreateModelMixin的create方法,来调用序列化器中定义的create方法,并将请求对象传入create中
        return self.create(request)

    # CreateAPIView:此视图子类仅提供post方法,但本视图需要实现浏览记录的获取,所以不能继承此视图子类
    def get(self, request):
        """获取并显示用户浏览记录"""
        # 获取用户id
        user_id = request.user.id

        # 取出用户所有的浏览记录信息
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)

        # 遍历sku_ids,并查询SKU数据库获取数据,并放入列表容器中进行序列化
        # 1.定义列表容器
        sku_list = []
        # 2.遍历sku_ids
        for sku_id in sku_ids:
            # 查询数据库获取对应商品信息
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)
        # 3.将需要进行序列化输出的数据放入序列化器中
        serializer_sku = SKUSerializer(sku_list, many=True)

        # 返回响应
        return Response(serializer_sku.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """自定义用户登录逻辑,并合并购物车"""

    def post(self, request, *args, **kwargs):

        # 调用父类的post方法,完成用户登录逻辑
        response = super(UserAuthorizeView, self).post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            # 调用合并购物车工具方法
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

            # 返回响应数据
            return response
